package com.mmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.mmall.common.ServerResponse;
import com.mmall.dao.ShippingMapper;
import com.mmall.pojo.Shipping;
import com.mmall.service.IShippingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Service("iShippingService")
public class ShippingServiceImpl implements IShippingService{


    @Autowired
    private ShippingMapper shippingMapper;

    @Override
    public ServerResponse addShipping(Integer userId, Shipping shipping) {

        //设置他的用户id
        shipping.setUserId(userId);

        //增加数据
        int insertCount = shippingMapper.insert(shipping);
        if (insertCount>0){

            Map map = Maps.newHashMap();
            map.put("ShippingId",shipping.getId());
            return  ServerResponse.createBySuccess("新增地址成功",map);
        }

        return ServerResponse.createByErrorMessage("新增地址失败");
    }

    @Override
    public ServerResponse deleteShipping(Integer userId, Integer shippingId) {

        //根据用户id删除对应的收货地址
        int shippingCount = shippingMapper.deleteByShippingIdAndUserId(userId, shippingId);
        if (shippingCount>0){
            return  ServerResponse.createBySuccessMessage("删除收货地址成功");
        }
        return  ServerResponse.createByErrorMessage("删除收货地址失败");

    }

    @Override
    public ServerResponse updateShipping(Integer userId, Shipping shipping) {

        shipping.setUserId(userId);

        int  shippingCount= shippingMapper.updateByShipping(shipping);
        if (shippingCount>0){
            return  ServerResponse.createBySuccessMessage("更新收货地址成功");
        }
        return  ServerResponse.createByErrorMessage("更新收货地址失败");
    }

    @Override
    public ServerResponse selectShipping(Integer userId, Integer shippingId) {


        //根据用户id删除对应的收货地址
        Shipping shipping = shippingMapper.selectByShippingIdUserId(userId, shippingId);
        if (shipping != null){
            return  ServerResponse.createBySuccess("查询收货地址成功",shipping);
        }
        return  ServerResponse.createByErrorMessage("查询收货地址失败");

    }

    @Override
    public ServerResponse selectShippingAll(Integer userId, Integer pageNum, Integer pageSize) {

        //初始化分页
        PageHelper.startPage(pageNum,pageSize );

        List<Shipping> shippingList = shippingMapper.selectByUserId(userId);

        if (shippingList != null){
            //把所有的地址进行分页排序
            PageInfo pageInfo = new PageInfo(shippingList);
            //返回结果
            return  ServerResponse.createBySuccess(pageInfo);
        }

        return ServerResponse.createByErrorMessage("查询所以收货地址失败");
    }
}
